package com.sunnyweather.android.ui.place

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.sunnyweather.android.MainActivity
import com.sunnyweather.android.databinding.FragmentPlaceBinding
import com.sunnyweather.android.ui.weather.WeatherActivity

class PlaceFragment : Fragment() {

    private var _binding: FragmentPlaceBinding? = null

    private val binding get() = _binding!!

    //连接界面与底层数据的中介者，生存周期器长于Activity
    val viewModel by lazy { ViewModelProvider(this).get(PlaceViewModel::class.java) }

    private lateinit var adapter: PlaceAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        //返回界面为：fragment_place.xml
        _binding = FragmentPlaceBinding.inflate(inflater, container, false)
        return binding.root
    }

    /**
     * 在MainActivity创建之后执行如下方法
     */
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)


        /**
         * 看看有没有之前缓存的信息，如果有之前保存的信息，那就直接用之前保存的信息
         */
        if (activity is MainActivity && viewModel.isPlaceSaved()) {
            val savedPlace = viewModel.getSavedPlace()
            val intent = Intent(context, WeatherActivity::class.java).apply {
                putExtra("location_lng", savedPlace.location.lng)
                putExtra("location_lat", savedPlace.location.lat)
                putExtra("place_name", savedPlace.name)
            }
            startActivity(intent)
            activity?.finish()
            return
        }

        //如果没有之前保存的信息，那么先设置RecyclerView
        val layoutManager = LinearLayoutManager(activity)
        binding.recyclerView.layoutManager = layoutManager
        adapter = PlaceAdapter(this, viewModel.placeList)
        binding.recyclerView.adapter = adapter

        //如果搜索框填入了地址，就执行以下操作
        binding.searchPlaceEdit.addTextChangedListener { editable ->
            val content = editable.toString()
            if (content.isNotEmpty()) {
                //PlaceViewModel中的searchLiveData所持有的值发生改变
                viewModel.searchPlaces(content)
            } else {
                binding.recyclerView.visibility = View.GONE
                binding.bgImageView.visibility = View.VISIBLE
                viewModel.placeList.clear()
                adapter.notifyDataSetChanged()
            }
        }

        /**
         * 为PlaceViewModel中的placeLiveData添加观察者，并设置相关方法
         * 观察者为这个PlaceFragment，变化的数据为result
         */
        viewModel.placeLiveData.observe(viewLifecycleOwner, Observer { result ->
            //result是根据输入的一个地点查询到的相关的多个地点的集合
            val places = result.getOrNull()
            //如果数据没变成空的
            if (places != null) {
                //显示出地址列表
                binding.recyclerView.visibility = View.VISIBLE
                //隐藏掉背景图片
                binding.bgImageView.visibility = View.GONE
                //清除之前的数据
                viewModel.placeList.clear()
                //添加上所有地点
                viewModel.placeList.addAll(places)
                //提醒显示地点列表的RecyclerView的数据适配器数据已更改
                //重新显示地点列表
                adapter.notifyDataSetChanged()
            } else {
                Toast.makeText(activity, "未能查询到任何地点", Toast.LENGTH_SHORT).show()
                result.exceptionOrNull()?.printStackTrace()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}